package com.sakiko.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

// 拦截器
// 步骤 1: 创建类实现拦截器接口 HandlerInterceptor
// 步骤 2: 选择重写方法
// 步骤 3: 配置放行和拦截的地址
public class ErrorInterceptor implements HandlerInterceptor {
    /**
     * 在目标 handler之前进行执行！
     * 可以设置进行拦截的动作，拦截要配合 请求转发和重定向跳转到提示页面
     *
     * @param request  本次请求的对象
     * @param response 本次响应对象
     * @param handler  调用的目标方法
     * @return 是否放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("ErrorInterceptor.preHandle");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler);
//        request.getRequestDispatcher().forward();
//        response.sendRedirect();
        return true;
    }

    /**
     * 在调用 handler之后执行，且 handler没有发生异常！
     * 后置的处理和完善 eg: fuck --> ****
     *
     * @param request      请求对象
     * @param response     响应对象
     * @param handler      调用 handler
     * @param modelAndView 返回的视图页面的封装对象，@ResponseBody不返回视图页面，这个对象为 null
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("ErrorInterceptor.postHandle");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", modelAndView = " + modelAndView);
    }

    /**
     * 在 springmvc流程处理完毕之后，将结果返回前端之前执行！
     * 对比 postHandler,它报错也执行！！！
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  调用 handler
     * @param ex       报错时为错误对象，否则为 null
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("ErrorInterceptor.afterCompletion");
        System.out.println("request = " + request + ", response = " + response + ", handler = " + handler + ", ex = " + ex);

    }
}

// 过滤器 filter -> javaEE  doFilter()
// 拦截器 interceptor -> spring mvc
// 拦截器优势: 能设置拦截地址和放行地址，更清晰 handler的调用的前后顺序